import axios from "axios";
import {Message, Loading} from "element-ui";

// window.localStorage.setItem('dominUrl', 'http://114.67.250.8');
console.log(window.location.href)
let url = window.location.href;
let a = unescape(url);
let str = a.split('/')
console.log(str[2])
if( str[2] == '192.168.3.27' ){
  //  内网
  window.localStorage.setItem('dominUrl', 'http://192.168.3.27');
}else{
  //  外网
  window.localStorage.setItem('dominUrl', 'http://116.131.8.40:8888');
}

let dominUrl = window.localStorage.getItem('dominUrl');
//loading设置 START
let loading;

function startLoading() {    //使用Element loading-start 方法
    loading = Loading.service({
        lock: true,
        text: '加载中……',
        background: 'rgba(0, 0, 0, 0.5)'
    })
}

function endLoading() {    //使用Element loading-close 方法
    loading.close()
}

let needLoadingRequestCount = 0;

export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        // startLoading();
    }
    needLoadingRequestCount++;
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--;
    if (needLoadingRequestCount === 0) {
        // endLoading();
    }
}

//loading END
var token = window.localStorage.getItem('token')
if (!token) {
    if (window.location.href.indexOf('token') !== -1) {
        let redirectUrl = window.location.href
        let arrAy = redirectUrl.split('?')
        let splt = arrAy[1].split('=')
        // let token = splt[1].replace('%20', ' ')
        token = "Bearer" + splt[1]
        console.log(token)
        window.localStorage.setItem('token', 'Bearer ' + token)
    } else {
        window.location.href = dominUrl + '/#/login?redirectUrl=' + dominUrl + '/garden_V2/#/visitor&appCode=GARDENSV2ITeFcKAH2XwjUAtyrm';
        // window.location.href = "http://114.67.250.8/#/login" + "?redirectUrl=http://114.67.250.8/garden_V2/#/visitor&appCode=GARDENSV2ITeFcKAH2XwjUAtyrm"
        // window.location.href = "http://116.131.8.40:8888/#/login" + "?redirectUrl=http://116.131.8.40:8888/garden_V2/#/visitor&appCode=GARDENSV2ITeFcKAH2XwjUAtyrm"
    }
}

axios.defaults.withCredentials = false;
// create an axios instance
const service = axios.create({
    headers: {
        "Content-Type": "application/json",
        "Authorization": token,
        "Tenant-Id": 10100
    },
    // process.env.VUE_APP_BASE_API  修改前
    //测试 http://114.67.250.8
    //正式 http://116.131.8.40:8888
    baseURL: dominUrl, // url = base url + request url  修改后
    withCredentials: false, // send cookies when cross-domain requests
    timeout: 50000 // request timeout
});

service.interceptors.request.use(
    config => {
        let url = window.location.href;
        //判断不是在登陆页面的话 其他页面token是否存在
        // if(url.indexOf("login") == -1 && !VueCookies.isKey('access_token')) {
        //     Message.error('身份验证已过期，请重新登陆');
        //     // let that = this;
        //     setTimeout(function () {
        //         window.location.reload();
        //     },1000)
        // }
        let reqData = config.data;
        for (let key in reqData) {
            if (reqData[key] === "") {
                delete reqData[key];
            }
        }
        config.data = reqData;
        showFullScreenLoading();
        // console.log(config);
        return config;
    },
    error => {
        // do something with request error
        console.log(error); // for debug
        return Promise.reject(error);
    }
);
// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code == 1) {
            tryHideFullScreenLoading();

            // Message.error('身份验证已过期，请重新登陆');
            // setTimeout(function () {
            //     window.location.reload();
            // },1000);
            // if(localStorage.getItem("token") == '' || localStorage.getItem("token") == null || localStorage.getItem("token") == undefined) {
            //     tryHideFullScreenLoading();
            //     // window.location.href = "http://localhost:8888/#/login";
            // } else {
            //     tryHideFullScreenLoading();
            //     Message.error('身份验证已过期，请重新登陆');
            //     localStorage.removeItem("token");
            //     localStorage.removeItem("teacherName");
            //     setTimeout(function () {
            //         window.location.href = g.domain + "/#/login";
            //     },1000);
            // }
            // return;
        } else {
            tryHideFullScreenLoading();
            return Promise.resolve(response.data);
        }
    },
    error => {
        tryHideFullScreenLoading();

        Message.error('网络异常，请稍后再试');
        setTimeout(function () {
            // window.location.reload();
        }, 1000);
        // Message.error('网络异常，请稍后再试');
        // setTimeout(function () {
        //     // window.location.reload();
        // },1000);
        // return Promise.reject(error);
        // return
        if (error) {
            if (error.response.status == 401) {
                window.location.href = dominUrl + '/#/login?redirectUrl=' + dominUrl + '/garden_V2/#/visitor&appCode=GARDENSV2ITeFcKAH2XwjUAtyrm';
                // window.location.href = "http://114.67.250.8/#/login" + "?redirectUrl=http://114.67.250.8/garden_V2/#/visitor&appCode=GARDENSV2ITeFcKAH2XwjUAtyrm"
                // window.location.href = "http://116.131.8.40:8888/#/login" + "?redirectUrl=http://116.131.8.40:8888/garden_V2/#/visitor&appCode=GARDENSV2ITeFcKAH2XwjUAtyrm"
            }
        }
        return Promise.reject(error)
    }
);

export default service;
